﻿using AutoMapper;
using D.Medicalcare.Domain.Entities;
using D.Medicalcare.ErrorCode;
using D.Medicalcare.Infrastructure.Interfaces;

using D.Medicalcare.Write.API.Application.Commands.ReserInstrucCommand;
using MediatR;

namespace D.Medicalcare.Write.API.Application.Handlers.ReserInstrucHarder
{
    public class AddReserInstrucHarder : IRequestHandler<AddReserInstrucCommand, APIResult<int>>
    {

        private readonly IMapper mapper;
        private IBaseRepository<ReserInstruc> repository;
        private readonly ILogger<AddReserInstrucHarder> logger;

        public AddReserInstrucHarder(IMapper mapper, IBaseRepository<ReserInstruc> repository, ILogger<AddReserInstrucHarder> logger)
        {
            this.mapper = mapper;
            this.repository = repository;
            this.logger = logger;
        }

        public async Task<APIResult<int>> Handle(AddReserInstrucCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<int> result = new APIResult<int>();
                var model = repository.GetAll().Where(x => x.ReserInstrucId > 0).Count();
                if (model == 0)
                {
                    var xi = mapper.Map<ReserInstruc>(request);
                    xi.IsDeleted = false;
                    var a = repository.AddAsync(xi).Result;
                    result.Code = APIEnum.Success;
                    result.Msg = "添加成功";
                    result.Data = a;
                    logger.LogInformation("新增预约成功");
                }
                else
                {
                    request.ReserInstrucId = 1;
                    var xi = mapper.Map<ReserInstruc>(request);

                    xi.ReserInstrucName = request.ReserInstrucName;
                    await repository.Update(xi);
                    result.Code = APIEnum.Success;
                    result.Msg = "修改成功";
                    result.Data = 1;
                    logger.LogError("修改预约成功");


                }
                return await Task.FromResult(result);

            }
            catch (Exception  ex)
            {
                logger.LogError("新增预约异常" + ex.Message);
                throw;
            }
        }
    }
}
